const log = (msg) => {
	console.log('%c弹幕机器人', 'background: rgb(255, 102, 0);  border-radius: 4px; color: #fff; padding: 2px 3px;', msg);
};

/**
 * 检查节点是否加载完成
 * @param {Function} cb 回调函数
 */
const loopCheckDOM = (selector, cb) => {
	log(`循环检查节点是否加载到 DOM：${config.chatList}`);
	const timer = setTimeout(() => {
		clearTimeout(timer);

		if ($(selector).length) {
			log(`节点已加载：${config.chatList}`);
			cb && cb();
		}
		else {
			loopCheckDOM(selector, cb);
		}
	}, 2e3);
};

const TTSMessage = {
	speak(msg) {
		if (window.localStorage.getItem('tts') == 1) {
			chrome.runtime.sendMessage({
				action: 'TTSMessage',
				content: msg,
			});
		}
	},
	turnOn() {
		window.localStorage.setItem('tts', 1);
	},
};

// const container = "#js-player-asideMain";

var ConfigMap = {
	"www.douyu.com": {
		form: "#js-player-asideMain .Chat",
		chatList: '#js-player-asideMain .layout-Player-asideMainTop',
		msgInput: "#js-player-asideMain .ChatSend-txt",
		sendBtn: "#js-player-asideMain .ChatSend-button",
	},
	"www.zhanqi.tv": {
		form: "#js-chat-control-panel > .room-chat-notice-layer",
		msgInput: ".js-chat-msg-input",
		sendBtn: "a.send-btn.js-chat-msg-btn",
	},
};

var host = window.location.host;
var config = ConfigMap[host];
var $msgInput = config.msgInput;
var $sendBtn = config.sendBtn;

var content = {
	// 执行入口
	init: function () {
		this.addMsgButton();

		/* 监听开启按钮 */
		chrome.runtime.onMessage.addListener(
			function (request, sender, sendResponse) {
				switch (request.action) {
					case "sendmsg":
						window.localStorage.setItem('sendmsg', request.content)
						log('sendmsg saved')
						break;
					case "wellcomemsg":
						window.localStorage.setItem('wellcomemsg', request.content)
						log('wellcomemsg saved')
						break;
					default:
						break;
				}
				sendResponse();
			});
	},

	Operation: function () {
		// var lastchatid=window.localStorage.getItem('lastchatid')
		// //查询最后一次上传messageid所在位置
		// lastchatidPostion=$('#chat_line_list').index($("span.text_cont,span.m").attr("chatid", lastchatid))

		var msgDoms = $('ul#js-barrage-list').children().not('.operated');
		var msglength = msgDoms.length;
		var randomi = Math.floor(Math.random() * msglength);

		msgDoms.each(function (i) {
			const self = $(this);
			var $nick = self.find('.Barrage-nickName')
			const nickName = $nick.text();

			var $chat = self.find('.Barrage-content')
			const chatId = $chat.data('chatid');
			const chatMessage = $chat.text().trim();

			self.addClass('operated'); // 标记处理
			window.localStorage.setItem('lastchatid', chatId);

			const msg = nickName + '说' + chatMessage;

			/*选项控制：语音 等。。。*/
			if (msglength > 5) {
				log('开启随机 TTS');
				if (randomi == i) {
					TTSMessage.speak(msg);
				}
			} else {
				TTSMessage.speak(msg);
			}
		});
	},

	/**
	 * 插入控制按钮
	 */
	addMsgButton: function () {
		const $chatList = $(config.chatList);

		if ($chatList.length) {
			const ButtonList = $('<div class="auto-msg-button" title="由【弹幕机器人】强势插入">\
				<button type="button" class="button-start extension-btn">开启监控弹幕</button>\
				<button type="button" class="button-send-msg extension-btn">刷屏</button>\
			</div>');

			const h = 40; // 插入节点的高度
			$chatList.css({
				bottom: (parseInt($chatList.css('bottom'), 10) || 89) + h, // 聊天列表向上收点空间
			});

			ButtonList.css({
				height: h,
				bottom: $('.layout-Player-chat').css('height'), // 给聊天框腾出空间
			});

			$chatList.after(ButtonList);
		}
		else {
			alert(`未找到节点:${config.form}`);
			log(`未找到节点:${config.form}`);
		}

		$(".auto-msg-button > .button-start").data('status', 0);

		var task;
		$(".button-start").on('click', function () {
			TTSMessage.turnOn();
			const $this = $(this);

			if ($this.data('status') == 0) {
				$this.data('status', 1); //1开启 0暂停中
				$this.text('开启中...')
				task = setInterval(content.Operation, 5e3)
				$(".shie-input").click()
				log('开启监控')
			}
			else {
				clearInterval(task);
				$(this).data('status', 0); //1开启 0暂停中
				$(this).text('开启监控')
				log('关闭')
			}
		});

		// 666刷屏
		var sendmsgtask;
		$(".button-send-msg").on('click', function () {
			if ($(this).data('status') == 0) {
				$(this).data('status', 1); //1开启 0暂停中
				$(this).text('刷屏中...')
				sendmsgtask = setInterval(function () {
					content.sendMsgTask();
				}, 3e3)
				log('开启刷屏')
			} else {
				clearInterval(sendmsgtask);
				$(this).data('status', 0); //1开启 0暂停中
				$(this).text('刷屏')
				log('关闭')
			}
		});

		/*进入房间自动发送欢迎信息*/
		setTimeout(function () {
			content.wellcomeMsg();
		}, 3e3)
	},

	sendMsgTask: function () {
		var myDate = new Date()
		let msg = window.localStorage.getItem('sendmsg') || '666666666666';
		if (msg === 'time') {
			var timeMsg = '【北京时间 ' + myDate.getHours() + ':' + myDate.getMinutes() + '】'
			msg = timeMsg;
		}
		var randommsg = ['.', '..', '...', ',', ',,', ',,,', '...', '.', '..', '`', ' '];
		this.sendMsg(msg + randommsg[(Math.floor(Math.random() * randommsg.length))]);
	},

	sendMsg(msg) {
		$($msgInput).val(msg);
		$($sendBtn).click();
	},

	wellcomeMsg: function () {
		var msg = window.localStorage.getItem('wellcomemsg') || "我来啦~"
		this.sendMsg(msg);
	},
};

$(document).ready(function () {
	loopCheckDOM(config.chatList, () => {
		setTimeout(() => { content.init(); }, 10e3);
	});
});
